package com.aidex.admin.controller.system;

import com.aidex.common.annotation.Log;
import com.aidex.common.core.controller.BaseController;
import com.aidex.common.core.domain.R;
import com.aidex.common.core.domain.entity.SysRole;
import com.aidex.common.core.domain.entity.SysUser;
import com.aidex.common.core.domain.model.LoginUser;
import com.aidex.common.enums.BusinessType;
import com.aidex.common.query.QueryGenerator;
import com.aidex.common.utils.SecurityUtils;
import com.aidex.common.utils.StringUtils;
import com.aidex.common.utils.poi.ExcelUtil;
import com.aidex.system.domain.SysUserRole;
import com.aidex.system.service.SysPostService;
import com.aidex.system.service.SysRoleService;
import com.aidex.system.service.SysUserService;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 用户信息
 */
@RestController
@RequestMapping("/system/user")
public class SysUserController extends BaseController<SysUserService> {

    @Autowired
    private SysRoleService roleService;

    @Autowired
    private SysPostService postService;

    /**
     * 获取用户列表
     */
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/list")
    public R page(SysUser user,
                  @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                  @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                  HttpServletRequest req) {
        QueryWrapper<SysUser> queryWrapper = QueryGenerator.initQueryWrapper(user, req.getParameterMap());
        Page<SysUser> page = new Page<>(pageNo, pageSize);
        IPage<SysUser> pageList = service.selectPage(page, queryWrapper);
        return R.data(pageList);
    }

    @Log(title = "用户管理" , businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('system:user:export')")
    @GetMapping("/export")
    public R export(SysUser user,
                    HttpServletRequest req) {
        QueryWrapper<SysUser> queryWrapper = QueryGenerator.initQueryWrapper(user, req.getParameterMap());
        List<SysUser> list = service.selectList(queryWrapper);
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        return util.exportExcel(list, "用户数据");
    }

    @Log(title = "用户管理" , businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('system:user:import')")
    @PostMapping("/importData")
    public R importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        List<SysUser> userList = util.importExcel(file.getInputStream());
        LoginUser loginUser = getLoginUser();
        String operName = loginUser.getUsername();
        String message = service.importUser(userList, updateSupport, operName);
        return R.success(message);
    }

    @GetMapping("/importTemplate")
    public R importTemplate() {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        return util.importTemplateExcel("用户数据");
    }

    /**
     * 根据用户编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping(value = {"/" , "/{userId}"})
    public R getInfo(@PathVariable(value = "userId" , required = false) String userId) {
        JSONObject ajax = new JSONObject();
        List<SysRole> roles = roleService.selectList(new QueryWrapper<>());
        ajax.put("roles" , SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        ajax.put("posts" , postService.selectList(new QueryWrapper<>()));
        if (StringUtils.isNotNull(userId)) {
            QueryWrapper wrapper = new QueryWrapper();
            wrapper.eq("u.id", userId);
            ajax.put("data" , service.selectById(userId));
        }
        return R.data(ajax);
    }

    /**
     * 新增用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:add')")
    @Log(title = "用户管理" , businessType = BusinessType.INSERT)
    @PostMapping
    public R add(@Validated @RequestBody SysUser user) {
        return R.status(service.insert(user));
    }

    /**
     * 修改用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理" , businessType = BusinessType.UPDATE)
    @PutMapping
    public R edit(@Validated @RequestBody SysUser user) {
        service.checkUserAllowed(user);
        return R.status(service.updateById(user));
    }

    /**
     * 删除用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:remove')")
    @Log(title = "用户管理" , businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R remove(@PathVariable("ids") String[] ids) {
        if (ArrayUtils.contains(ids, getUserId())) {
            return R.fail("当前用户不能删除");
        }
        return R.status(service.deleteBatchIds(Arrays.asList(ids)));
    }

    /**
     * 重置密码
     */
    @PreAuthorize("@ss.hasPermi('system:user:resetPwd')")
    @Log(title = "用户管理" , businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public R resetPwd(@RequestBody JSONObject params) {
        SysUser dbUser = service.selectById(params.getString("id"));
        service.checkUserAllowed(dbUser);
        return R.status(service.resetUserPwd(dbUser.getUserName(), SecurityUtils.encryptPassword(params.getString("password"))));
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理" , businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public R changeStatus(@RequestBody SysUser user) {
        service.checkUserAllowed(user);
        user.setUpdateBy(SecurityUtils.getUsername());
        return R.status(service.updateById(user));
    }

    /**
     * 校验角色编码是否存在
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理" , businessType = BusinessType.CHECK)
    @GetMapping("/checkUserNameUnique")
    public R checkUserNameUnique(SysUser user) {
        Map<String, String> checkMap = new HashMap<String, String>(1);
        try {
            service.checkUserNameUnique(user);
            checkMap.put("code" , "1");
        } catch (Exception e) {
            checkMap.put("code" , "2");
        }
        return R.data(checkMap);
    }

    /**
     * 校验角色编码是否存在
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理" , businessType = BusinessType.CHECK)
    @GetMapping("/checkEmailUnique")
    public R checkEmailUnique(SysUser user) {
        Map<String, String> checkMap = new HashMap<String, String>(1);
        try {
            service.checkEmailUnique(user);
            checkMap.put("code" , "1");
        } catch (Exception e) {
            checkMap.put("code" , "2");
        }
        return R.data(checkMap);
    }

    /**
     * 校验角色编码是否存在
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理" , businessType = BusinessType.CHECK)
    @GetMapping("/checkPhoneUnique")
    public R checkPhoneUnique(SysUser user) {
        Map<String, String> checkMap = new HashMap<String, String>(1);
        try {
            service.checkPhoneUnique(user);
            checkMap.put("code" , "1");
        } catch (Exception e) {
            checkMap.put("code" , "2");
        }
        return R.data(checkMap);
    }

    /**
     * 通用选人页面根据用户ID
     *
     * @return
     */
    @PostMapping(value = {"/selectUserListByUserIds"})
    public R selectUserListByUserIds(@Validated @RequestBody JSONObject params) {
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        wrapper.in("id", params.getString("userIds").split(";"));
        return R.data(service.selectList(wrapper));
    }

    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/roleUserList")
    public R roleUserPage(@RequestParam(name = "userNameOrName", required = false) String codeOrName,
                          @RequestParam(name = "roleId") String roleId,
        @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
        @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(codeOrName)) {
            queryWrapper.and(wrapper ->
                    wrapper.like("t.name", codeOrName).or().
                    like("t.name_en", codeOrName).or().
                    like("t.no", codeOrName).or().
                    like("t.user_name", codeOrName).or().
                    like("t.nick_name", codeOrName));
        }
        queryWrapper.eq("ur.role_id", roleId);
        queryWrapper.eq("t.del_flag", "0");
        Page<SysUser> page = new Page<>(pageNo, pageSize);
        IPage<SysUser> pageList = service.selectPageByRoleId(page, queryWrapper);
        return R.data(pageList);
    }

    @PreAuthorize("@ss.hasPermi('system:user:add')")
    @Log(title = "用户角色管理" , businessType = BusinessType.INSERT)
    @PostMapping("/addRoleUser")
    public R addRoleUser(@Validated @RequestBody SysUserRole sysUserRole) {
        return R.status(service.insertRoleUser(sysUserRole));
    }

    /**
     * 刷新缓存
     */
    @PreAuthorize("@ss.hasPermi('system:config:remove')")
    @Log(title = "用户管理" , businessType = BusinessType.CLEAN)
    @DeleteMapping("/refreshCache")
    public R refreshCache() {
        service.refreshCache();
        return R.status(true);
    }
}
